from common import TestYamlRead, TestRequests, TestLogGing
import pytest
import os
import time


# 日志记录
logger = TestLogGing.LoggerHandler(file=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                    f"log\\{time.strftime('%Y%m%d')}.log"))

# 读取测试用例数据
def read_case_data(file_name):
    case_data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), f"case_data\\{file_name}")
    return TestYamlRead.yaml_read(case_data_path)

# 读取hots
def read_host(file_name):
    host_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), file_name)
    return TestYamlRead.yaml_read(host_path)

# 退出登录
def log_out(token):
    api_url = read_case_data("register_login.yaml")["logout_data"][0]
    run = TestRequests.HttpPack().requests_api(url=read_host("config.yaml")["host"]["service_host"] + api_url["api"],
                                            method=api_url["method"],
                                            headers=token)
    return run

# 测试开始结束需执行的函数
@pytest.fixture(scope="session")
def stare_end():
    print("—————————————————开始执行用例—————————————————")
    yield "测试执行中"
    print("—————————————————用例执行结束—————————————————")

# 客户端token
@pytest.fixture(scope="session")
def get_token():
    header_json = read_case_data("register_login.yaml")["log_in"][0]
    log_json = {"username": 18180695114, "password": 123456}
    token = {}
    run = TestRequests.HttpPack().requests_api(url=read_host("config.yaml")["host"]["service_host"] + header_json["api"],
                                                   method=header_json["method"],
                                                   json=log_json)
    token["token"] = run["data"]["token"]
    yield token
    log_out(token)

# web后台token
@pytest.fixture(scope="session")
def web_token():
    header_json = read_case_data("register_login.yaml")["log_in"][0]
    data_json = {"username": "supper","password": "123456","userType": 1}
    token = {}
    run = TestRequests.HttpPack().requests_api(url=read_host("config.yaml")["host"]["service_host"] + header_json["api"],
                                                   method=header_json["method"],
                                                   json=data_json)
    token["token"] = run["data"]["token"]
    yield token
    log_out(token)
